<template>
  <div class="medication">
    <ivue-crud
      :data="medications"
      :dialogOpen.sync="dialogOpen"
      :editData="editData"
      :isUpdate="isUpdate"
      :option="option"
      :searchForm.sync="searchForm"
      :show-page="false"
      :syncDataReady="syncDataReady"
      :tableLoading="loading"
      :title="title"
      @on-create="onCreate"
      @on-page-change="pageChange"
      @on-page-size-change="pageSizeChange"
      @on-update="onUpdate"
      @search="doSearch"
      dialog-width="60%"
      ref="ivueCrud"
    >
      <div slot="headerMenu">
        <Button :size="option.searchSize" @click="historySearch" custom-icon="iconfont " type="warning">历史版本</Button>
        <Button :loading="loading" :size="option.searchSize" @click="doSearch" custom-icon="iconfont icon-shuaxin" type="primary">刷新</Button>
        <Button :size="option.searchSize" @click="create" custom-icon="iconfont icon-plus" type="success">新增</Button>
      </div>
    </ivue-crud>
  </div>
</template>

<script>
export default {
  name: 'medication',
  components: {},
  data() {
    return {
      type: 'MedicationRequest',
      pageLoading: false,
      isUpdate: false,
      showTest: false,
      loading: false,
      editData: {},
      pageSize: 10,
      pageNo: 0,
      deptData: [],
      searchText: '',
      syncDataReady: true,
      resource: 'medication',
      title: '医嘱',
      dialogOpen: false,
      searchForm: {},
      drugDic: [
        {
          drugCode: '#100001',
          drugName: '阿莫西林',
          itemCode: '1111101',
          itemName: '阿莫西林(人民制药厂) 颗粒 24粒/1盒',
          mdDrugCode: '900001',
          mdDrugName: '阿莫西林',
          manufacturer: '人民制药厂',
          formCode: '1',
          formName: '颗粒',
          amountNum: '24',
          amountNumUnit: '粒',
          amountDen: '1',
          amountDenUnit: '盒'
        }
      ]
    }
  },
  computed: {
    medications() {
      let jData = []
      this.$store.state.medication.medications.forEach(entry => {
        let re = entry.resource
        if (re.total && re.total.myStringValue == '0') return
        jData.push({
          url: re.id.myStringValue,
          id: re.id.myUnqualifiedId,
          versionId: re.id.myUnqualifiedVersionId,
          status: re.status ? re.status.myStringValue : '',
          /*patientId: '1111',
            encId: '1111-1',*/
          patientName: re.subject ? (re.subject.display ? re.subject.display.myStringValue : '') : '',
          groupId: re.groupIdentifier && re.groupIdentifier.value ? re.groupIdentifier.value.myStringValue : '',
          orderNo: re.identifier && re.identifier[0].value ? re.identifier[0].value.myStringValue : '',
          icdCode:
            re.reasonCode && re.reasonCode[0].coding && re.reasonCode[0].coding[0] && re.reasonCode[0].coding[0].code
              ? re.reasonCode[0].coding[0].code.myStringValue
              : '',
          icdName:
            re.reasonCode && re.reasonCode[0].coding && re.reasonCode[0].coding[0] && re.reasonCode[0].coding[0].display
              ? re.reasonCode[0].coding[0].display.myStringValue
              : '',
          categoryCode:
            re.category && re.category[0].coding && re.category[0].coding[0] && re.category[0].coding[0].code
              ? re.category[0].coding[0].code.myStringValue
              : '',
          categoryName:
            re.category && re.category[0].coding && re.category[0].coding[0] && re.category[0].coding[0].display
              ? re.category[0].coding[0].display.myStringValue
              : '',
          authoredOn: re.authoredOn && re.authoredOn.myStringValue ? this.formatDate(re.authoredOn.myStringValue, 'yyyy-mm-dd hh:mm:ss') : '',
          drugCode: re.medication && re.medication.reference ? re.medication.reference.myStringValue : '',
          drugName: re.medication && re.medication.display ? re.medication.display.myStringValue : '',
          requesterName: re.requester && re.requester.display ? re.requester.display.myStringValue : '',
          note: re.note && re.note[0].text ? re.note[0].text.myStringValue : '',
          days:
            re.dosageInstruction &&
            re.dosageInstruction.length &&
            re.dosageInstruction[0].timing &&
            re.dosageInstruction[0].timing.repeat &&
            re.dosageInstruction[0].timing.repeat.bounds &&
            re.dosageInstruction[0].timing.repeat.bounds.value
              ? re.dosageInstruction[0].timing.repeat.bounds.value.myStringValue
              : '',
          frequencyCode:
            re.dosageInstruction &&
            re.dosageInstruction.length &&
            re.dosageInstruction[0].timing &&
            re.dosageInstruction[0].timing.code &&
            re.dosageInstruction[0].timing.code.coding &&
            re.dosageInstruction[0].timing.code.coding.length &&
            re.dosageInstruction[0].timing.code.coding[0].code
              ? re.dosageInstruction[0].timing.code.coding[0].code.myStringValue
              : '',
          frequencyName:
            re.dosageInstruction &&
            re.dosageInstruction.length &&
            re.dosageInstruction[0].timing &&
            re.dosageInstruction[0].timing.code &&
            re.dosageInstruction[0].timing.code.coding &&
            re.dosageInstruction[0].timing.code.coding.length &&
            re.dosageInstruction[0].timing.code.coding[0].display
              ? re.dosageInstruction[0].timing.code.coding[0].display.myStringValue
              : '',
          routeCode:
            re.dosageInstruction &&
            re.dosageInstruction.length &&
            re.dosageInstruction[0].route &&
            re.dosageInstruction[0].route.coding &&
            re.dosageInstruction[0].route.coding.length &&
            re.dosageInstruction[0].route.coding[0].code
              ? re.dosageInstruction[0].route.coding[0].code.myStringValue
              : '',
          routeName:
            re.dosageInstruction &&
            re.dosageInstruction.length &&
            re.dosageInstruction[0].route &&
            re.dosageInstruction[0].route.coding &&
            re.dosageInstruction[0].route.coding.length &&
            re.dosageInstruction[0].route.coding[0].display
              ? re.dosageInstruction[0].route.coding[0].display.myStringValue
              : '',
          dosageQuantity:
            re.dosageInstruction &&
            re.dosageInstruction.length &&
            re.dosageInstruction[0].doseAndRate &&
            re.dosageInstruction[0].doseAndRate.length &&
            re.dosageInstruction[0].doseAndRate[0].dose &&
            re.dosageInstruction[0].doseAndRate[0].dose.value
              ? re.dosageInstruction[0].doseAndRate[0].dose.value.myStringValue
              : '',
          dosageUnit:
            re.dosageInstruction &&
            re.dosageInstruction.length &&
            re.dosageInstruction[0].doseAndRate &&
            re.dosageInstruction[0].doseAndRate.length &&
            re.dosageInstruction[0].doseAndRate[0].dose &&
            re.dosageInstruction[0].doseAndRate[0].dose.unit
              ? re.dosageInstruction[0].doseAndRate[0].dose.unit.myStringValue
              : '',
          dispenseQuantity:
            re.dispenseRequest && re.dispenseRequest.quantity && re.dispenseRequest.quantity.value
              ? re.dispenseRequest.quantity.value.myStringValue
              : '',
          dispenseUnit:
            re.dispenseRequest && re.dispenseRequest.quantity && re.dispenseRequest.quantity.unit
              ? re.dispenseRequest.quantity.unit.myStringValue
              : ''
        })
      })
      return jData
    },
    option() {
      return {
        resource: this.resource,
        searchSize: 'small',
        dialog: true,
        inline: true,
        searchForm: true,
        formGroup: true,
        border: true,
        column: [
          {
            label: '#',
            width: 50,
            type: 'index'
          },
          {
            label: 'ID',
            prop: 'id',
            search: true
          },
          {
            label: '版本',
            prop: 'versionId'
          },
          {
            label: '患者ID',
            prop: 'patientId',
            hideInTb: true,
            editable: true,
            rules: [{ required: true, message: '请输入患者ID', trigger: 'blur' }]
          },
          {
            label: '就诊ID',
            prop: 'encId',
            hideInTb: true,
            rules: [{ required: true, message: '请输入患者就诊ID', trigger: 'blur' }]
          },
          {
            label: '姓名',
            prop: 'patientName',
            editable: true,
            rules: [{ required: true, message: '请输入姓名', trigger: 'blur' }]
          },
          {
            label: '诊断',
            prop: 'icdCode',
            type: 'select',
            dicData: [{ value: 'J20', label: '急性支气管炎' }, { value: 'J06.903', label: '上呼吸道感染' }],
            labelInValue: true,
            syncLabel: 'icdName',
            editable: true,
            filterable: true,
            rules: [{ required: true, message: '请输入诊断', trigger: 'change' }],
            render: (h,param)=>{
              return h('span',param.row.icdName)
            }
          },
          {
            label: '处方单号',
            prop: 'groupId',
            editable: true,
            rules: [{ required: true, message: '请输入处方单号', trigger: 'blur' }]
          },
          {
            label: '项目序号',
            prop: 'orderNo',
            editable: true,
            rules: [{ required: true, message: '请输入项目序号', trigger: 'blur' }]
          },
          {
            label: '处方分类',
            prop: 'categoryCode',
            type: 'select',
            dicData: [{ value: 'outpatient', label: '门诊' }],
            labelInValue: true,
            syncLabel: 'categoryName',
            editable: true,
            rules: [{ required: true, message: '请选择处方分类', trigger: 'change' }],
            render: (h,param)=>{
              return h('span',param.row.categoryName)
            }
          },
          {
            label: '药品名称',
            prop: 'drugCode',
            type: 'select',
            search: true,
            editable: true,
            dicData: this.drugDic,
            onchange: this.changeDrug,
            selectLabelKey: 'drugName',
            selectValueKey: 'drugCode',
            filterable: true,
            rules: [{ required: true, message: '请选择药品', trigger: 'change' }],
            render: (h,param)=>{
              return h('span',param.row.drugName)
            }
          },
          {
            label: '开单医生',
            prop: 'requesterName',
            editable: true
          },
          {
            label: '开单时间',
            prop: 'authoredOn'
          },
          {
            label: '备注',
            prop: 'note',
            editable: true
          },
          {
            label: '天数',
            prop: 'days',
            editable: true,
            render: (h,param)=>{
              return h('span',param.row.days+'天')
            }
          },
          {
            label: '用药频率',
            prop: 'frequencyCode',
            type: 'select',
            editable: true,
            labelInValue: true,
            syncLabel: 'frequencyName',
            dicData: [{ value: 'Qd', label: '一日一次' }, { value: 'Bid', label: '一日两次' }],
            filterable: true,
            rules: [{ required: true, message: '请选择用药频率', trigger: 'change' }],
            render: (h,param)=>{
              return h('span',param.row.frequencyName)
            }
          },
          {
            label: '用药途径',
            prop: 'routeCode',
            type: 'select',
            editable: true,
            labelInValue: true,
            syncLabel: 'routeName',
            dicData: [{ value: '1', label: '口服' }, { value: '2', label: '静脉输液' }],
            filterable: true,
            rules: [{ required: true, message: '请选择用药途径', trigger: 'change' }],
            render: (h,param)=>{
              return h('span',param.row.routeName)
            }
          },
          {
            label: '剂量',
            prop: 'dosageQuantity',
            editable: true,
            rules: [{ required: true, message: '请输入剂量', trigger: 'blur' }],
            render: (h,param)=>{
              return h('span',param.row.dosageQuantity+param.row.dosageUnit)
            }
          },
          {
            label: '剂量单位',
            prop: 'dosageUnit',
            type: 'select',
            editable: true,
            hideInTb: true,
            filterable: true,
            dicData: [{ value: '片', label: '片' }, { value: '粒', label: '粒' }, { value: '瓶', label: '瓶' }, { value: '盒', label: '盒' }],
            rules: [{ required: true, message: '请选择剂量单位', trigger: 'change' }]
          },
          {
            label: '发药数量',
            prop: 'dispenseQuantity',
            editable: true,
            rules: [{ required: true, message: '请输入发药数量', trigger: 'blur' }],
            render: (h,param)=>{
              return h('span',param.row.dispenseQuantity+param.row.dispenseUnit)
            }
          },
          {
            label: '发药数量单位',
            prop: 'dispenseUnit',
            type: 'select',
            editable: true,
            hideInTb: true,
            filterable: true,
            dicData: [{ value: '片', label: '片' }, { value: '粒', label: '粒' }, { value: '瓶', label: '瓶' }, { value: '盒', label: '盒' }],
            rules: [{ required: true, message: '请选择发药数量单位', trigger: 'change' }]
          },
          {
            label: '操作',
            width: 100,
            type: 'render',
            render: (h, params) => {
              return h(
                'div',
                {
                  class: 'btn-wrap'
                },
                [
                  h(
                    'a',
                    {
                      on: {
                        click: () => {
                          this.update(params.row)
                        }
                      }
                    },
                    '编辑'
                  ),
                  h('Divider', {
                    props: { type: 'vertical' }
                  }),
                  h(
                    'a',
                    {
                      on: {
                        click: () => {
                          this.remove(params.row)
                        }
                      }
                    },
                    '删除'
                  )
                ]
              )
            }
          }
        ]
      }
    }
  },
  created() {
    this.doSearch()
  },
  methods: {
    historySearch() {
      if (!this.searchForm.id) {
        this.$Message.error('请输入ID')
        return
      }
      this.loading = true
      this.$store
        .dispatch('getHistoryMedicationList', {
          type: this.type,
          id: this.searchForm.id
        })
        .then(() => {
          this.loading = false
        })
    },
    changeDrug(code) {
      let drug = this.drugDic.filter(item => (item.drugCode = code))
      this.editData = Object.assign(this.editData, drug[0])
    },
    doSearch(searchForm) {
      searchForm = (!(searchForm instanceof MouseEvent) && searchForm) || this.searchForm
      this.loading = true
      this.$store
        .dispatch('getMedicationList', {
          id: this.searchForm.id,
          paramName: 'medication',
          value: this.searchForm.drugName,
          type: this.type
        })
        .then(() => {
          console.log('res')
          this.loading = false
        })
    },
    remove(row) {
      this.$Modal.confirm({
        title: '删除确认',
        content: '<p>是否确认删除当前数据?</p>',
        onOk: () => {
          this.pageLoading = true
          this.$store
            .dispatch('deleteMedication', Object.assign(row, {type: this.type}))
            .then(() => {
              this.pageLoading = false
              this.$Message.success('删除成功')
              this.searchForm = {id:row.id}
              this.doSearch()
            })
            .catch(() => {
              this.pageLoading = false
            })
        },
        onCancel: () => {}
      })
    },
    create() {
      this.editData = {
        patientId: localStorage.getItem('patientId'),
        encId: '1111-1',
        patientName: '张三',
        groupId: 'p1111',
        orderNo: 'p1111-1',
        icdCode: 'J20',
        icdName: '急性支气管炎',
        categoryCode: 'outpatient',
        categoryName: '门诊',
        drugCode: '#100001',
        drugName: '阿莫西林',
        itemCode: '1111101',
        itemName: '阿莫西林(人民制药厂) 颗粒 24粒/1盒',
        mdDrugCode: '900001',
        mdDrugName: '阿莫西林',
        manufacturer: '人民制药厂',
        formCode: '1',
        formName: '颗粒',
        amountNum: '24',
        amountNumUnit: '粒',
        amountDen: '1',
        amountDenUnit: '盒',
        requesterName: '李四',
        note: '请遵医嘱',
        days: '2',
        frequencyCode: 'Bid',
        frequencyName: '一日两次',
        routeCode: '1',
        routeName: '口服',
        dosageQuantity: '2',
        dosageUnit: '片',
        dispenseQuantity: '2',
        dispenseUnit: '盒'
      }
      this.isUpdate = false
      this.dialogOpen = true
    },

    onCreate(row) {
      this.syncDataReady = false
      this.$store
        .dispatch('createMedication', row)
        .then(res => {
          this.syncDataReady = true
          this.searchForm.id = res.data.myId.myUnqualifiedId
          this.doSearch()
          window.setTimeout(() => {
            this.dialogOpen = false
            this.$Message.success(`新增${this.title}-${row.drugName}成功`)
          }, 200)
        })
        .catch(err => {
          this.syncDataReady = true
          this.$Message.error(err.message)
        })
    },
    update(row) {
      this.editData = row
      this.dialogOpen = true
      this.isUpdate = true
    },
    onUpdate(row) {
      this.syncDataReady = false
      this.$store
        .dispatch('updateMedication', row)
        .then(() => {
          this.syncDataReady = true
          this.doSearch()
          window.setTimeout(() => {
            this.dialogOpen = false
            this.$Message.success(`更新${this.title}-${row.drugName}成功`)
          }, 200)
        })
        .catch(() => {
          this.syncDataReady = true
        })
    },
    pageChange(pageNo) {
      this.pageNo = pageNo
      this.doSearch()
    },
    pageSizeChange(pageSize) {
      this.pageSize = pageSize
      this.doSearch()
    },
    formatDate(date, format) {
      if (!date) {
        console.error('formatDate函数date参数不可为空!')
        return ''
      }

      if (format === 'yyyy-mm-dd hh:mm:ss') {
        date = date instanceof Date || new Date(date)
        let years = date.getFullYear()
        let month = this.addZero(date.getMonth() + 1)
        let days = this.addZero(date.getDate())
        let hours = date.getHours()
        let min = date.getMinutes()
        let sec = date.getSeconds()

        return `${years}-${month}-${days} ${hours}:${min}:${sec}`
      }
    },
    addZero(temp) {
      if (temp < 10) return '0' + temp
      else return temp
    }
  }
}
</script>

<style scoped lang="less">
.medication {
  height: 100%;
}

.pane-form {
  max-width: 600px;
  margin: 20px;
}

.menu-btn {
  float: right;
  position: relative;

  :hover {
    cursor: pointer;
  }
}
</style>
